<!--
  * 出库单
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form :model="queryForm" labelAlign="left">
      <a-row :gutter="[8, 10]">
        <!-- <a-col :span="5.5">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.create_time" @search="onSearch" />
          </a-form-item>
        </a-col> -->
        <a-col :span="{ sm: 7, md: 6 }">
          <a-form-item label="出库日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.outbound_time" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="出库仓库" name="warehouse" class="smart-margin-bottom0">
            <Select name="Warehouse" v-model:value="queryForm.warehouse" :fetch-params="selectFetchParams.warehouse" placeholder="请选择仓库" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="出库类型" class="smart-margin-bottom0">
            <EnumSelect enum-name="RELATED_TYPE_ENUM" v-model:value="queryForm.related_type" placeholder="出库类型" @submit="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="配送方式" class="smart-margin-bottom0">
            <EnumSelect enum-name="IS_SELF" v-model:value="queryForm.is_self" placeholder="配送方式" @submit="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="5">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery" v-privilege="'goods:query'">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
            <SearchFormCollapse v-model="expand" />
          </a-button-group>
        </a-col>
        <template v-if="expand">
          <a-col :span="4">
            <a-form-item label="出库状态" class="smart-margin-bottom0">
              <EnumSelect enum-name="PICK_STATUS_ENUM" v-model:value="queryForm.status" placeholder="出库状态" @submit="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="供应商" name="supplier" class="smart-margin-bottom0">
              <Select name="Supplier" v-model:value="queryForm.supplier" placeholder="请选择供应商" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="门店" class="smart-margin-bottom0">
              <a-input v-model:value.trim="queryForm.store" placeholder="门店" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="单据编号" class="smart-margin-bottom0">
              <a-input v-model:value.trim="queryForm.no" placeholder="单据编号" allow-clear />
            </a-form-item>
          </a-col>
        </template>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="onExport" type="primary" v-privilege="'goods:exportGoods'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange, getCheckboxProps: getCheckboxPropsChange }">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.title === '源订单号'">
            <template v-if="Number(record.discounted_amount) !== Number(record.order_detail_amount) && record.related_type === 'Order'">
              <CopyText :text="text">
                <a @click="detail(record)">{{ text + ' ' }} </a>
              </CopyText>
              <a-tag color="error">减免</a-tag>
            </template>
            <template v-else>
              <CopyText :text="text">
                <a @click="detail(record)">{{ text }}</a>
              </CopyText>
            </template>
          </template>
          <template v-if="column.dataIndex === 'related_type'">
            <span>
              {{ getDescByValue('RELATED_TYPE_ENUM', text) }}
              <a-tag color="orange" v-if="record.related.is_self === 1" style="margin-left: 5px">自提</a-tag>
            </span>
          </template>
          <template v-if="column.dataIndex === 'warehouse_name'">
            <span
              >{{ text }}<span v-if="record?.warehouse_attribute_type">({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', record?.warehouse_attribute_type) }})</span>
            </span>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="TagColor[text]">{{ getDescByValue('PICK_STATUS_ENUM', Number(text)) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'customer'">
            <div style="width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap">{{ record.customer?.name ?? record.customer?.store_name }}</div>
          </template>
          <template v-if="column.dataIndex === 'order_amount'">
            <span>{{ Number(text).toFixed(2) }}</span>
          </template>
          <template v-if="column.dataIndex === 'order_agree_amount'">
            <span>{{ Number(text).toFixed(2) }}</span>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="detail(record)" type="link" style="color: #97999c" v-privilege="'goods:update'">详情</a-button>
              <!-- <template v-if="record.status === 1 && (ReceiveType.includes(record.related_type) || record.related.is_self === 1)">
                <a-button @click="deleteGoods(record)" danger type="link" v-privilege="'goods:delete'">出库</a-button>
              </template> -->
              <a-button @click="print(record)" type="link" v-privilege="'goods:update'">打印</a-button>
            </div>
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <a-table-summary-cell :index="0">总计</a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.totalNum }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.totalAmount }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.totalAgreeAmount }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.totalServiceAmount }}</a-typography-text>
              </a-table-summary-cell>
              <!-- <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.totalPartnerFee }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.totalOperationFee }}</a-typography-text>
              </a-table-summary-cell> -->
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </div>
    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>

    <!---------- 详情 begin ----------->
    <SalesOutboundDetailsModal ref="detailRef" />
    <!---------- 详情 end ----------->
    <SalesOutboundPrintModal ref="printRef" />
  </a-card>
</template>
<script setup lang="ts">
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import SalesOutboundDetailsModal from './components/sales-outbound-details-modal.vue'
import SalesOutboundPrintModal from './components/sales-outbound-print-modal.vue'
import SearchFormCollapse from '@/components/support/search-form-collapse/index.vue'
import { message, Modal } from 'ant-design-vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import { outOrderApi } from '@/api/business/storage/outbound-api'
import { PAGE_SIZE_OPTIONS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import { errorSentry } from '@/lib/error-sentry'
import TableOperator from '@/components/support/table-operator/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import Select from '@/components/business/select/index.vue'
import _ from 'lodash'
import { useQuery } from '@/hooks/web/use-query-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
import { WAREHOUSE_TYPE, WAREHOUSE_ATTRIBUTE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'
const appConfigStore = useAppConfigStore()
const loadingStore = useLoadingStore()
const { getDescByValue, getValueDescList } = useEnums()

// ----------------------------- tag出库状态 -----------------------------
enum TagColor {
  'processing' = 1,
  'success',
  'warning',
  'error'
}
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY, expand } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = computed(() => [
  {
    title: '源订单号',
    dataIndex: ['related', 'no'],
    width: appConfigStore.$state.compactFlag ? 150 : 180
  },
  {
    title: '出库类型',
    dataIndex: 'related_type'
  },
  {
    title: '门店/供应商',
    dataIndex: 'customer',
    width: 180
  },
  {
    title: '出库仓库',
    dataIndex: 'warehouse_name',
    width: 180
  },
  {
    title: '出库状态',
    dataIndex: 'status',
    width: 100
  },
  {
    title: '出库时间',
    dataIndex: 'outbound_time'
  },
  {
    title: '商品数量',
    dataIndex: 'order_number',
    width: 100
  },
  {
    title: '订单金额',
    dataIndex: 'order_amount',
    width: 120
  },
  {
    title: '货值金额',
    dataIndex: 'order_agree_amount',
    width: 140
  },
  {
    title: '服务费',
    dataIndex: 'order_service_amount',
    width: 140
  },
  {
    title: '创建者',
    dataIndex: ['creator', 'username']
  },
  {
    title: '订单时间',
    dataIndex: 'create_time'
  },
  {
    title: '备注',
    dataIndex: ['related', 'remark'],
    width: 120
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: appConfigStore.$state.compactFlag ? 150 : 170
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const total_amount = ref({
  totalAmount: 0,
  totalAgreeAmount: 0,
  totalOperationFee: 0,
  totalPartnerFee: 0,
  totalServiceAmount: 0,
  totalNum: 0
})
const { queryForm, queryFormOp, tableData, tableLoading, total, resetQuery, onSearch, queryData } = useQuery({
  fetchDataApi: async ({ op, filter, ...params }) => {
    const data = {
      ...params,
      ...filter,
      type: 1
    }
    const res = await outOrderApi.queryOutOrderList(data)
    total_amount.value.totalAmount = Number(res.data.totalAmount).toFixed(2)
    total_amount.value.totalAgreeAmount = Number(res.data.totalAgreeAmount).toFixed(2)
    total_amount.value.totalPartnerFee = Number(res.data.totalPartnerFee).toFixed(2)
    total_amount.value.totalOperationFee = Number(res.data.totalOperationFee).toFixed(2)
    total_amount.value.totalServiceAmount = _.sum([res.data.totalPartnerFee, res.data.totalOperationFee]).toFixed(2)
    total_amount.value.totalNum = res.data.totalNum

    const dataMoud = res.data.list.data.map((item) => {
      const a = Number(item.partner_fee) * 1000000
      const b = Number(item.operation_fee) * 1000000
      const result = (a + b) / 1000000
      return Object.assign({}, item, {
        order_service_amount: result
      })
    })
    console.log(dataMoud)
    return {
      list: dataMoud,
      total: res.data.list.total
    }
  },
  queryFormFilter: {
    no: '',
    store: '',
    warehouse: null,
    goods_name: '',
    supplier: null,
    dealer: null,
    status: null,
    related_type: null,
    // create_time: DEFAULT_TIME_RANGE.value,
    outbound_time: DEFAULT_TIME_RANGE.value,
    is_self: null
  },
  queryFormOp: {
    no: QUERY_FORM_OP['模糊查询'],
    store: QUERY_FORM_OP['模糊查询'],
    warehouse: QUERY_FORM_OP['模糊查询'],
    goods_name: QUERY_FORM_OP['模糊查询'],
    supplier: QUERY_FORM_OP['模糊查询'],
    dealer: QUERY_FORM_OP['模糊查询'],
    status: QUERY_FORM_OP['全等查询'],
    related_type: QUERY_FORM_OP['全等查询'],
    // create_time: QUERY_FORM_OP['范围查询'],
    outbound_time: QUERY_FORM_OP['范围查询'],
    is_self: QUERY_FORM_OP['全等查询']
  }
})

onActivated(() => {
  queryData()
})

// Select查询参数
const selectFetchParams = {
  warehouse: {
    filter: {
      warehouse_type: WAREHOUSE_TYPE.FIXED.value,
      attribute_type: [WAREHOUSE_ATTRIBUTE_TYPE.WAREHOUSE.value, WAREHOUSE_ATTRIBUTE_TYPE.TEMPORARY.value]
    },
    op: {
      warehouse_type: QUERY_FORM_OP['全等查询'],
      attribute_type: QUERY_FORM_OP['IN查询'] // 正库/处理库
    },
    fields: 'id,name'
  }
}

// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = (goodsData) => {
  detailRef.value.showDrawer(goodsData)
}
// ---------------------------- 打印 ----------------------------
const printRef = ref()

const print = async (goodsData) => {
  const res = await outOrderApi.detail({ id: goodsData.id })
  printRef.value.showDrawer(goodsData, res.data)
}
// ---------------------------- 出库----------------------------

function deleteGoods(goodsData) {
  Modal.confirm({
    title: '提示',
    content: '确定要出库【' + goodsData.no + '】吗?',
    okText: '出库',
    okType: 'danger',
    onOk() {
      singleDelete(goodsData)
    },
    cancelText: '取消',
    onCancel() {}
  })
}

async function singleDelete(goodsData) {
  try {
    loadingStore.show()
    const res = await outOrderApi.queryOrderConfirm({ id: goodsData.id })
    message.success(res.msg)
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}
// ---------------------------- 批量生成拣货单 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([])

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys
}

function getCheckboxPropsChange(record) {
  return { disabled: record.pick_status == 2 }
}
// ------------------------------- 导出和导入 ---------------------------------
// 导出
function onExport() {
  const { page, limit, ...filter } = queryForm.value
  const data = {
    ...filter
  }
  outOrderApi.exportXlsx(data)
}
</script>
